﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Kojarskiy;
using Kojarskiy.Core;
using Kojarskiy.Models;
using SiteMap = Kojarskiy.Models.SiteMap;

namespace Kojarskiy.Controllers
{
    [Authorize(Roles = "Administrators")]
    public class SiteMapController : Controller
    {
        const string PageNamePattern = "^[0-9A-Za-z/-]+$";
        private KojarskiyDbEntities context = new KojarskiyDbEntities();
        //
        // GET: /SiteMap/

        public ActionResult Index(int? rootId)
        {
            SiteMap rootNode;
            if (rootId == null)
            {
                rootNode = context.SiteMap.First(x => x.ParentId == null && x.Culture == Localization.Current);
                ViewBag.RootId = rootNode.SiteMapId;
                rootId = rootNode.SiteMapId;
            }
            else
            {
                rootNode = context.SiteMap.FirstOrDefault(x => x.SiteMapId == rootId && x.Culture == Localization.Current);
                ViewBag.RootId = rootNode.SiteMapId;
            }

            var preRoot = rootNode.ParentId;
            ViewBag.PreRootId = preRoot;

            ViewBag.OrderId = 0;
            var sitemap = context.SiteMap.Where(x => x.ParentId == rootId).OrderBy(x => x.Order);
            List<SiteMap> result = sitemap.ToList();

            if (rootNode.ParentId == null) result.Add(rootNode);

            return View(result);
        }

        //
        // GET: /SiteMap/Create
        public ActionResult Create(int rootId)
        {
            ViewData["ParentId"] = rootId;
            return View();
        } 

        //
        // POST: /SiteMap/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(SiteMap sitemap)
        {
            if (ModelState.IsValid)
            {
                var regex = new Regex(PageNamePattern);
                if (regex.IsMatch(sitemap.Path))
                {
                    sitemap.Controller = "Home";
                    sitemap.Action = "Page";
                    sitemap.Culture = Localization.Current;

                    context.SiteMap.Add(sitemap);
                    context.SaveChanges();

                    context.Entry(sitemap).State = EntityState.Modified;
                    sitemap.Order = sitemap.SiteMapId;
                    context.SaveChanges();
                    
                }
                else
                {
                    ModelState.AddModelError("", "Неправильный путь страницы");
                    ViewData["ParentId"] = sitemap.ParentId;
                    return View("Create"); 
                }
                return RedirectToAction("Index", new { rootId = sitemap.ParentId }); 
            }

            ViewBag.RootNode = sitemap.ParentId;
            ViewBag.RootId = new SelectList(context.SiteMap, "SiteMapId", "PageName", sitemap.ParentId);
            return View(sitemap);
        }
        
        //
        // GET: /SiteMap/Edit/5
        public ActionResult Edit(int id, string returnUrl)
        {
            SiteMap sitemap = context.SiteMap.Single(s => s.SiteMapId == id);
            ViewBag.RootNode = sitemap.ParentId;
            ViewBag.returnUrl = returnUrl;
            ViewBag.RootId = new SelectList(context.SiteMap, "SiteMapId", "PageName", sitemap.ParentId);
            return View(sitemap);
        }

        //
        // POST: /SiteMap/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(SiteMap sitemap, string returnUrl, IEnumerable<HttpPostedFileBase> files, string tbHeader, string tbFooter, string tbScripts)
        {
            if (ModelState.IsValid)
            {
                if (sitemap.ParentId != null)
                {
                    var regex = new Regex(PageNamePattern);
                    var isMatch = regex.IsMatch(sitemap.Path);
                    if (isMatch)
                    {
                        context.Entry(sitemap).State = EntityState.Modified;
                        sitemap.Culture = Localization.Current;
                        context.SaveChanges();
                        if (!string.IsNullOrEmpty(returnUrl)) Response.Redirect(returnUrl);
                        KojarskiyApplication.Message = new Message(MessageType.Success, "Изменение страницы успешно произведено!");
                        return RedirectToAction("Index", new { rootId = sitemap.ParentId });
                    }
                    else
                    {
                        KojarskiyApplication.Message = new Message(MessageType.Warning, "Неправильный путь страницы!");
                        return View("Edit", sitemap);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(tbHeader)) SettingsManager.SaveSettingsItem("DATA_HEADER", tbHeader);
                    if (!string.IsNullOrEmpty(tbFooter)) SettingsManager.SaveSettingsItem("DATA_FOOTER", tbFooter);
                    if (!string.IsNullOrEmpty(tbScripts)) SettingsManager.SaveSettingsItem("DATA_SCRIPTS", tbScripts);

                    try
                    {
                        if (files != null)
                        {
                            foreach (var file in files)
                            {
                                if (file != null)
                                {
                                    var image = new Gallery()
                                    {
                                        SiteMapId = 1,
                                        Path = "Home",
                                        ThumbPath = "Home",
                                        Description = ""
                                    };
                                    context.Gallery.Add(image);
                                    context.SaveChanges();
                                    context.Entry(image).State = EntityState.Modified;
                                    string thumbPath = "";
                                    image.Path = FileHelper.UploadPhoto(file, "Home", image.GalleryId, out thumbPath, false);
                                    image.ThumbPath = thumbPath;
                                    context.SaveChanges();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        
                        KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                    }

                    foreach (var key in Request.Form.AllKeys)
                    {
                        if (key.StartsWith("imagedesc"))
                        {
                            var value = Request.Form[key];
                            var id = Convert.ToInt32(key.Substring("imagedesc-".Length));
                            var image = context.Gallery.FirstOrDefault(x => x.GalleryId == id);
                            if (image != null)
                            {
                                context.Entry(image).State = EntityState.Modified;
                                image.Description = value;
                                context.SaveChanges();
                            }
                        }
                        if (key.StartsWith("url"))
                        {
                            var value = Request.Form[key];
                            var id = Convert.ToInt32(key.Substring("url-".Length));
                            var image = context.Gallery.FirstOrDefault(x => x.GalleryId == id);
                            if (image != null)
                            {
                                context.Entry(image).State = EntityState.Modified;
                                image.Url = value;
                                context.SaveChanges();
                            }
                        }
                    }

                    context.Entry(sitemap).State = EntityState.Modified;
                    sitemap.Path = "/";
                    sitemap.Culture = Localization.Current;
                    context.SaveChanges();
                    KojarskiyApplication.Message = new Message(MessageType.Success, "Изменение страницы успешно произведено!");
                    return RedirectToAction("Index", new { rootId = sitemap.ParentId });
                }
            }
            ViewBag.RootNode = sitemap.ParentId;
            ViewBag.RootId = new SelectList(context.SiteMap, "SiteMapId", "PageName", sitemap.ParentId);
            return View(sitemap);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult OrderDown(int siteMapId)
        {
            var sitemap = context.SiteMap.FirstOrDefault(x => x.SiteMapId == siteMapId);
            int i = 1;
            SiteMap changed = null;

            while (changed == null && i < context.SiteMap.Count(x => x.ParentId == sitemap.ParentId))
            {
                if (context.SiteMap.Where(x => x.ParentId == sitemap.ParentId).FirstOrDefault(x => x.Order == sitemap.Order + i) != null)
                {
                    changed = context.SiteMap.Where(x => x.ParentId == sitemap.ParentId).FirstOrDefault(x => x.Order == sitemap.Order + i);
                }
                else i++;
            }
            if (sitemap != null && changed != null)
            {
                var newOrder = changed.Order;

                context.Entry(changed).State = EntityState.Modified;
                changed.Order = sitemap.Order;
                context.SaveChanges();

                context.Entry(sitemap).State = EntityState.Modified;
                sitemap.Order = newOrder;
                context.SaveChanges();
            }
            return null;
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult OrderUp(int siteMapId)
        {
            var sitemap = context.SiteMap.FirstOrDefault(x => x.SiteMapId == siteMapId);
            int i = 1;
            SiteMap changed = null;
            if (sitemap != null)
            {
                while (changed == null && i < context.SiteMap.Count(x => x.ParentId == sitemap.ParentId))
                {
                    var current = context.SiteMap.Where(x => x.ParentId == sitemap.ParentId).FirstOrDefault(x => x.Order == sitemap.Order - i);
                    if (current != null) changed = current;
                    else i++;
                }
                try
                {
                    if (changed != null)
                    {
                        var newOrder = changed.Order;

                        context.Entry(changed).State = EntityState.Modified;
                        changed.Order = sitemap.Order;
                        context.SaveChanges();

                        context.Entry(sitemap).State = EntityState.Modified;
                        sitemap.Order = newOrder;
                        context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                }
            }
            return null;
        }

        [HttpPost]
        public ActionResult DeleteSliderImage(int galleryId)
        {
            Gallery image = context.Gallery.Single(s => s.GalleryId == galleryId);
            context.Gallery.Remove(image);
            context.SaveChanges();
            return null;
        }

        //
        // GET: /SiteMap/Delete/5
        public ActionResult Delete(int id)
        {
            SiteMap sitemap = context.SiteMap.Single(s => s.SiteMapId == id);
            return View(sitemap);
        }

        //
        // POST: /SiteMap/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            SiteMap sitemap = context.SiteMap.Single(s => s.SiteMapId == id);
            context.SiteMap.Remove(sitemap);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveLayout(int siteMapId, int categoryId)
        {
            string layout = "";
            foreach (var key in Request.Form.AllKeys)
            {
                if (key.StartsWith("layout"))
                {
                    var value = Request.Form[key];
                    layout += "key=" + key + "&value=" + value + "&";
                }                
            }
            Blocks block = null;

            if (categoryId > 0)
            {
                block = context.Blocks.FirstOrDefault(x => x.CategoryId == categoryId && x.SiteMapId == siteMapId);
            }
            else
            {
                block = context.Blocks.FirstOrDefault(x => x.SiteMapId == siteMapId && x.CategoryId == 0);
            }

            if(block != null) context.Blocks.Remove(block);

            layout = layout.TrimEnd('&');
            block = new Blocks();
            block.BlockTypeId = 1;
            block.CategoryId = categoryId;
            block.SiteMapId = siteMapId;
            block.Layout = layout;
            context.Blocks.Add(block);
            context.SaveChanges();
            return null;
        }
        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}